<template>
  <view class="home-comm">
    <!-- 搜索框 -->
    <view class="search-bar">
      <uv-search
        v-model="searchQuery"
        :placeholder="isOutStock ? '点击选择客户姓名' : '点击选择厂商'"
        shape="round"
        :clearabled="true"
        :action-text="'X'"
        disabled="true"
        @search="(e) => queryHanderEvent('search', e)"
        @clear="queryHanderEvent('clear')"
        @confirm="(e) => queryHanderEvent('search', e)"
        @custom="(e) => queryHanderEvent('clear', e)"
        @click="(e) => queryHanderEvent('click', e)"
      />
      <!-- 下拉建议列表 -->
      <view
        class="dropdown-list"
        v-if="showDropdown && filteredList.length > 0"
      >
        <uv-list>
          <uv-list-item
            v-for="(item, index) in filteredList"
            :key="index"
            :title="item.title"
            :clickable="true"
            @click="() => dropDownEvent('selectMenu', item)"
          />
        </uv-list>
      </view>
      <!-- <uv-drop-down
        ref="dropDownRef"
        sign="dropDown_1"
        :defaultValue="[0, '0', 'all']"
        @click="(e) => dropDownEvent('selectMenu', e)"
        :placeholder="isOutStock ? '客户姓名' : '厂商'"
        :trigger="['click']"
        :arrow="true"
        :arrowDirection="['down', 'up']"
      >
        <uv-drop-down-item name="order" type="2" label="综合排序" value="all">
        </uv-drop-down-item>
      </uv-drop-down>
      <uv-drop-down-popup
        sign="dropDown_1"
        @popupChange="(e) => dropDownEvent('popupChange', e)"
      >
        <view
          style="width: 750rpx; height: 300rpx; background-color: #fff"
        ></view>
      </uv-drop-down-popup> -->
    </view>
    <z-paging
      :paging-style="{
        height: 'calc(100% - (114rpx + env(safe-area-inset-bottom)))',
        marginTop: '80rpx',
      }"
      ref="paging"
      v-model="dataList"
      @query="queryList"
      v-if="!skeletonsLoading"
    >
      <!-- 自定义下拉刷新view(如果use-custom-refresher为true且不设置下面的slot="refresher"，此时不用获取refresherStatus，会自动使用z-paging自带的下拉刷新view) -->

      <!-- 注意注意注意！！字节跳动小程序中自定义下拉刷新不支持slot-scope，将导致custom-refresher无法显示 -->
      <!-- 如果是字节跳动小程序，请参照sticky-demo.vue中的写法，此处使用slot-scope是为了减少data中无关变量声明，降低依赖 -->
      <template #refresher="{ refresherStatus }">
        <!-- 此处的custom-refresh为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，下拉刷新就显示什么view -->
        <CustomRefresher :status="refresherStatus" />
      </template>
      <!-- 自定义没有更多数据view -->
      <template #loadingMoreNoMore>
        <!-- 此处的custom-nomore为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，没有更多数据就显示什么view -->
        <CustomNomore />
      </template>

      <!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
      <view class="list-container">
        <view
          v-for="(item, index) in dataList"
          :key="index"
          class="card-item"
          @click="itemClick(item)"
        >
          <view class="status-tag">
            <view
              class="status-tag-item"
              @click="
                buttonHanderEvent(isOutStock ? 'outStockRP' : 'inStockRP', item)
              "
              :style="{
                background: '#91C8F8',
              }"
            >
              点击{{ isOutStock ? "收款" : "付款" }}
            </view>
          </view>
          <view class="card-header">
            <text class="title">
              {{
                isOutStock
                  ? item.customerName
                  : `${item.manufacturerName} ${item.specification}`
              }}
            </text>
          </view>

          <view class="card-content">
            <template v-if="isOutStock">
              <view class="detail-row">
                <text>订单数量：</text>
                <text>{{ item.orderCount || 0 }}￥</text>
              </view>
              <view class="detail-row">
                <text>总应付金额：</text>
                <text>{{ item.totalPayableAmount || 0 }}￥</text>
              </view>
              <view class="detail-row">
                <text>总已付金额：</text>
                <text>{{ item.totalPaidAmount || 0 }}￥</text>
              </view>
              <view class="detail-row">
                <text>总销售数量：</text>
                <text>{{ item.totalQuantity || 0 }}￥</text>
              </view>
              <view class="detail-row">
                <text>客户电话：</text>
                <text>{{ item.customerPhone || "无" }}</text>
              </view>
            </template>
            <template v-else>
              <view class="detail-row">
                <text>总金额：</text>
                <text>{{ item.totalAmount || 0 }}￥</text>
              </view>
              <view class="detail-row">
                <text>总已付金额：</text>
                <text>{{ item.totalPaidAmount || 0 }}￥</text>
              </view>
              <view class="detail-row">
                <text>入库记录数：</text>
                <text>{{ item.recordCount || 0 }}</text>
              </view>
              <view class="detail-row">
                <text>总入库数量：</text>
                <text>{{ item.totalQuantity || 0 }}</text>
              </view>
              <view class="detail-row">
                <text>订单开始时间：</text>
                <text>{{ item.lastInStockDate || "" }}</text>
              </view>
            </template>
          </view>
          <view class="card-footer">
            <!-- <uv-button
              class="payment-button"
              type="primary"
              @click="
                buttonHanderEvent(isOutStock ? 'inStockRP' : 'outStockRP', item)
              "
              :customStyle="{
                borderRadius: '10rpx',
                width: '180rpx',
              }"
            >
              {{ isOutStock ? "收款" : "付款" }}
            </uv-button> -->
          </view>
        </view>
      </view>
    </z-paging>
    <uv-modal
      :key="modalData?.type"
      ref="modalAddRef"
      :title="modalData?.title"
      :content="modalData?.content"
      :show-confirm-button="false"
      :close-on-click-overlay="false"
    >
      <view class="payment-dialog" v-if="currentData">
        <view class="payment-summary">
          <view class="summary-item">
            <text class="label">订单总额：</text>
            <text class="amount"
              >¥{{
                currentData?.totalPayableAmount || currentData?.totalAmount
              }}</text
            >
          </view>
          <view class="summary-item">
            <text class="label">已付金额：</text>
            <text class="amount paid">¥{{ currentData?.totalPaidAmount }}</text>
          </view>
          <view class="summary-item">
            <text class="label">剩余金额：</text>
            <text class="amount remaining"
              >¥{{
                (currentData.totalAmount || currentData?.totalPayableAmount) -
                currentData.totalPaidAmount
              }}</text
            >
          </view>
        </view>
        <view class="payment-input-area">
          <text class="payment-label">付款金额：</text>
          <uv-input
            v-model="paymentAmount"
            type="number"
            placeholder="请输入付款金额"
            :clearable="true"
          ></uv-input>
        </view>
        <view class="payment-buttons">
          <uv-button
            @click="buttonHanderEvent('modalclose')"
            :customStyle="{
              borderRadius: '10rpx',
              width: '180rpx',
            }"
          >
            取消
          </uv-button>
          <uv-button
            type="primary"
            @click="buttonHanderEvent('modalconfirm')"
            :disabled="paymentAmount <= 0 || !paymentAmount"
            :customStyle="{
              borderRadius: '10rpx',
              width: '180rpx',
            }"
          >
            确认
          </uv-button>
        </view>
      </view>
    </uv-modal>
    <uv-notify ref="notifyRef"></uv-notify>
  </view>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import request from "../../../http/request.js";
import CustomNomore from "./components/CustomNomore/index.vue";
import CustomRefresher from "./components/CustomRefresher/index.vue";
import { getList } from "@/config/APIS.js";
import { getStatusName } from "@/utils/utils.js";

import cloudConfig from "@/config/uniCloudConfig.js";
// const uniCloudSalesManager = uniCloud.importObject("outStockManager"); //销售表
// const uniCloudSalesManager = cloudConfig.getCloudObject("outStockManager");
// const uniCloudStockManager = cloudConfig.getCloudObject("inStockManager");
const uniCloudOutAndInStockCommon = cloudConfig.getCloudObject(
  "outAndInStockCommon"
);

const paging = ref(null);
const filteredList = ref([]);
// v-model绑定的这个变量不要在分页请求结束中自己赋值，直接使用即可
const dataList = ref([]);
const searchQuery = ref("");

const loading = ref(true);
const showDropdown = ref(false);

const modalAddRef = ref();
const notifyRef = ref();
const modalData = ref();
const currentData = ref({});
const paymentAmount = ref();
const isOutStock = computed(() => props?.pageData?.type === "outStockPayment");
const props = defineProps();

const getData = async (pageNum, pageSize) => {
  const userInfo = uni.getStorageSync("userInfo");
  if (props?.pageData?.type == "outStockPayment") {
    // 查询当前登陆人的数据
    let salesList =
      await uniCloudOutAndInStockCommon.getOutStockManagerAggregatedData(
        searchQuery.value || "",
        userInfo._id,
        pageNum,
        pageSize
      );
    console.log(salesList, "===salesList=outStock==");
    paging.value.complete(salesList.data);
  }
  if (props?.pageData?.type == "inStockPayment") {
    let manufacturer = searchQuery.value?.split("-")?.[0] || "";
    let specification = searchQuery.value?.split("-")?.[1] || "";
    // 查询当前登陆人的数据
    let salesList =
      await uniCloudOutAndInStockCommon.getInStockManagerAggregatedData(
        manufacturer,
        specification,
        userInfo._id,
        pageNum,
        pageSize
      );
    // let salesList = await uniCloudOutSalesManager.getTenantSalesRecords('test1', pageNum, pageSize)
    console.log(salesList, "===salesList=inStock==");
    paging.value.complete(salesList.data);
  }
};

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = async (pageNum, pageSize) => {
  // 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
  // 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
  // 模拟请求服务器获取分页数据，请替换成自己的网络请求

  // paging.value.complete(demooutStockData)
  // 模拟数据
  // const userInfo = uni.getStorageSync("userInfo");
  // if (props?.pageData?.type == "outStockPayment") {
  //   // 查询当前登陆人的数据
  //   let salesList =
  //     await uniCloudOutAndInStockCommon.getOutStockManagerAggregatedData(
  //       "",
  //       userInfo._id,
  //       pageNum,
  //       pageSize
  //     );
  //   console.log(salesList, "===salesList=outStock==");
  //   paging.value.complete(salesList.data);
  // }
  // if (props?.pageData?.type == "inStockPayment") {
  //   // 查询当前登陆人的数据
  //   let salesList =
  //     await uniCloudOutAndInStockCommon.getInStockManagerAggregatedData(
  //       "",
  //       "",
  //       userInfo._id,
  //       pageNum,
  //       pageSize
  //     );
  //   // let salesList = await uniCloudOutSalesManager.getTenantSalesRecords('test1', pageNum, pageSize)
  //   console.log(salesList, "===salesList=inStock==");
  //   paging.value.complete(salesList.data);
  // }
  await getData(pageNum, pageSize);

  // const params = {
  // 	pageNo: pageNum,
  // 	pageSize: pageSize,
  // 	type: 1
  // }
  // request.queryList(params).then(res => {
  // 	// 将请求的结果数组传递给z-paging
  // 	paging.value.complete(res.data.list);
  // }).catch(res => {
  // 	// 如果请求失败写this.$refs.paging.complete(false);
  // 	// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
  // 	// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
  // 	paging.value.complete(false);
  // })
};

const eventDateHandle = (eType, eData) => {
  console.log(eType, eData, "==eventDateHandle===eType, eData");
};

const dropDownEvent = async (eType, eData) => {
  console.log(eType, eData, "==selectMenuEvent===eType, eData");
  switch (eType) {
    case "selectMenu":
      searchQuery.value = eData.title;
      await getData(1, 10);
      showDropdown.value = false;
      break;
    default:
      break;
  }
};

const buttonHanderEvent = async (eType, eData) => {
  console.log(eType, eData, "==queryHanderEvent===eType, eData");
  switch (eType) {
    case "modalclose":
      modalAddRef?.value?.close();
      break;
    case "inStockRP":
      currentData.value = eData;
      modalData.value = {
        type: "inStockRP",
        title: "汇款时请检查无误后点确认！",
        content: "",
        data: eData,
      };
      nextTick(() => {
        modalAddRef?.value?.open();
      });
      break;
    case "outStockRP":
      currentData.value = eData;
      modalData.value = {
        type: "outStockRP",
        title: "汇款时请检查无误后点确认！",
        content: "",
        data: eData,
      };
      nextTick(() => {
        modalAddRef?.value?.open();
      });
      break;
    case "modalconfirm":
      console.log(modalData.value, "===modalData.value===");
      const userInfo = uni.getStorageSync("userInfo");
      switch (modalData.value.type) {
        case "inStockRP":
          // 收款
          // 处理paymentAmount 有可能为 0开头的整数需要给提示
          if (paymentAmount.value.startsWith("0")) {
            notifyRef.value.warning("付款金额不能以0开头");
            return;
          }
          // 处理paymentAmount 有可能为小数需要给提示
          if (paymentAmount.value.includes(".")) {
            notifyRef.value.warning("付款金额不能为小数");
            return;
          }
          if (
            paymentAmount.value >
            currentData.value.totalAmount - currentData.value.totalPaidAmount
          ) {
            notifyRef.value.warning("付款金额不能大于剩余金额");
            return;
          }

          // 二次确认
          uni.showModal({
            title: "确认付款",
            content: `确认付款金额为 ¥${paymentAmount.value} 吗？`,
            success: async (res) => {
              try {
                if (res.confirm) {
                  console.log(modalData.value, "====modalData.value===");
                  console.log(currentData.value, "====currentData.value===");
                  console.log(
                    paymentAmount.value,
                    "====paymentAmount.value==="
                  );

                  let newCurrentData = {
                    ...currentData.value,
                    paymentDate: new Date().getTime(),
                    paymentAmount: paymentAmount.value,
                  };
                  console.log(
                    newCurrentData,
                    "=inStockRP===newCurrentData=1=="
                  );
                  let res =
                    await uniCloudOutAndInStockCommon.batchPaymentInStock(
                      newCurrentData,
                      userInfo._id
                    );

                  console.log(res, "====res===");

                  if (res.success) {
                    notifyRef.value.success("付款成功");
                    paging?.value?.reload();
                    currentData.value = null;
                    paymentAmount.value = null;
                    modalData.value = null;
                    modalAddRef?.value?.close();
                  } else {
                    notifyRef.value.error("付款失败");
                  }
                }
              } catch (error) {
                console.log(error, "====error===");
              }
            },
          });
          break;
        case "outStockRP":
          // 收款
          // 处理paymentAmount 有可能为 0开头的整数需要给提示
          if (paymentAmount.value.startsWith("0")) {
            notifyRef.value.warning("收款金额不能以0开头");
            return;
          }
          // 处理paymentAmount 有可能为小数需要给提示
          if (paymentAmount.value.includes(".")) {
            notifyRef.value.warning("收款金额不能为小数");
            return;
          }
          if (
            paymentAmount.value >
            currentData.value.totalPayableAmount -
              currentData.value.totalPaidAmount
          ) {
            notifyRef.value.warning("收款金额不能大于剩余金额");
            return;
          }

          // 二次确认
          uni.showModal({
            title: "确认收款",
            content: `确认收款金额为 ¥${paymentAmount.value} 吗？`,
            success: async (res) => {
              try {
                if (res.confirm) {
                  console.log(modalData.value, "====modalData.value===");
                  console.log(currentData.value, "====currentData.value===");
                  console.log(
                    paymentAmount.value,
                    "====paymentAmount.value==="
                  );

                  let newCurrentData = {
                    ...currentData.value,
                    paymentAmount: paymentAmount.value,
                    paymentDate: new Date().getTime(),
                  };
                  console.log(
                    newCurrentData,
                    "=outStockRP===newCurrentData=1=="
                  );
                  let res =
                    await uniCloudOutAndInStockCommon.batchPaymentOutStock(
                      newCurrentData,
                      userInfo._id
                    );

                  console.log(res, "====res===");

                  if (res.success) {
                    notifyRef.value.success("收款成功");
                    paging?.value?.reload();
                    currentData.value = null;
                    paymentAmount.value = null;
                    modalData.value = null;
                    modalAddRef?.value?.close();
                  } else {
                    notifyRef.value.error("收款失败");
                  }
                }
              } catch (error) {
                console.log(error, "====error===");
              }
            },
          });

          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
};
const queryHanderEvent = async (eType, eData) => {
  console.log(eType, eData, "==queryHanderEvent===eType, eData");
  switch (eType) {
    case "clear":
      searchQuery.value = "";
      paging?.value?.reload();
      break;
    case "click":
      showDropdown.value = !showDropdown.value;
      break;
    case "blur":
    case "search":
    case "confirm":
      searchQuery.value = eData;
      if (props?.pageData?.type == "outStockPayment") {
        // 查询当前登陆人的数据
        const userInfo = uni.getStorageSync("userInfo");
        let salesList =
          await uniCloudOutAndInStockCommon.getOutStockManagerAggregatedData(
            eData || "",
            userInfo._id,
            1,
            10
          );
        console.log(salesList, "=queryHanderEvent==salesList=outStock==");
        paging.value.complete(salesList.data);
      }
      if (props?.pageData?.type == "inStockPayment") {
        // queryData.value.customer_name = eData;
        // 查询当前登陆人的数据
        const userInfo = uni.getStorageSync("userInfo");
        let salesList =
          await uniCloudOutAndInStockCommon.getInStockManagerAggregatedData(
            "",
            "",
            userInfo._id,
            1,
            10
          );
        console.log(salesList, "=queryHanderEvent==salesList=outStock==");
        paging.value.complete(salesList.data);
      }
      break;
    default:
      break;
  }
};

onLoad((option) => {
  console.log(option, "==home=option====");
  paging?.value?.reload();
});

const getInit = async () => {
  let fetchData = [];
  const userInfo = uni.getStorageSync("userInfo");
  if (props?.pageData?.type == "outStockPayment") {
    fetchData = (
      await uniCloudOutAndInStockCommon.fetchOutStockCustomerList(userInfo?._id)
    )?.data.map((item) => {
      item.title = item.customer_name;
      return item;
    });
  }
  if (props?.pageData?.type == "inStockPayment") {
    fetchData = (
      await uniCloudOutAndInStockCommon.fetchInStockMaterialSpecs(userInfo?._id)
    )?.data.map((item) => {
      item.title = `${item.manufacturer}-${item.specification}`;
      return item;
    });
  }

  filteredList.value = fetchData;

  console.log("getInit====home======", fetchData);
};
// 点击列表的每一项
const itemClick = (item) => {
  console.log(item, "===item");
};

onShow(() => {
  console.log("show home");
  paging?.value?.reload();
});

// watch(() => props.pageData, () => {
// 	console.log( props,"===== props.pageData props.pageData");
// 	console.log( props.pageData.type,"===== type.type type.type");
// 	getInit()
// }, {
// 	immediate: true,
// 	deep: true
// })

onMounted(() => {
  console.log(props, "===== props.pageData props.pageData");
  getInit();
  // uni.showLoading({
  // 	title: "加载中",
  // 	mask: true
  // });
  // getInit()
  // console.log(props, "===props===props===");
  // setTimeout(() => {
  // 	uni.hideLoading()
  // }, 1500)
});
</script>

<style scoped lang="scss">
.home-comm {
  height: 100%;
  overflow: hidden;
  display: flex;
  width: 100%;
  flex-direction: column;
  align-items: center;
  .search-bar {
    width: 100%;
    padding: 10rpx;
    background: #fff;
    position: relative;
    .dropdown-list {
      position: absolute;
      z-index: 10;
      width: 90%;
      left: 5%;
      margin-top: 4rpx;
      background-color: #fff;
      border: 1px solid #eee;
      border-radius: 10rpx;
      max-height: 400rpx;
      overflow-y: auto;
    }
  }

  .list-container {
    padding: 20rpx 36rpx 20rpx 20rpx;
    .card-item {
      background: #fff;
      border-radius: 16rpx;
      padding: 24rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      position: relative;
      .status-tag {
        width: 100%;
        height: 40rpx;
        position: relative;

        .status-tag-item {
          font-size: 28rpx;
          line-height: 70rpx;
          color: #fff;
          text-align: center;
          width: 160rpx;
          height: 60rpx;
          /* 透明遮罩+soft-light 给标签打上一层高光 */
          background: linear-gradient(
              135deg,
              rgba(255, 255, 255, 0.4),
              transparent
            )
            #91c8f8;
          background-blend-mode: soft-light;
          display: inline-block;
          border-radius: 15rpx 15rpx 0 15rpx;
          position: absolute;
          right: -48rpx;
          top: -16rpx;

          &::after {
            position: absolute;
            content: "";
            clip-path: polygon(0rpx 0rpx, 0rpx 24rpx, 24rpx 0rpx);
            width: 24rpx;
            height: 24rpx;
            right: 0;
            bottom: -24rpx;
            /* 颜色变暗：filter滤镜、半透明遮罩 */
            /* 使用filter滤镜 使颜色变暗 */
            /*filter: brightness(.6);*/
            /* 给颜色上添加一个半透明遮罩实现颜色变暗 */
            background: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3));
            background-color: inherit;
            /* 继承 */
          }
        }
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
    }

    .title {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
      max-width: 70%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .card-content {
      background: #f8f9fb;
      padding: 20rpx;
      border-radius: 12rpx;
    }

    .detail-row {
      display: flex;
      justify-content: space-between;
      margin: 12rpx 0;
      font-size: 28rpx;
      color: #666;

      text:first-child {
        color: #999;
      }
    }
  }
  .payment-dialog {
    padding: 10rpx;
    width: 100%;

    .payment-summary {
      background-color: #f8f8f8;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 30rpx;

      .summary-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          color: #666;
          font-size: 28rpx;
        }

        .amount {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;

          &.paid {
            color: #19be6b;
          }

          &.remaining {
            color: #fa3534;
          }
        }
      }
    }

    .payment-input-area {
      display: flex;
      align-items: center;
      padding: 0 10rpx;

      .payment-label {
        font-size: 28rpx;
        color: #333;
        margin-right: 20rpx;
        white-space: nowrap;
      }

      :deep(.uv-input) {
        flex: 1;

        .uv-input__input {
          height: 80rpx;
          font-size: 28rpx;
        }
      }
    }
  }

  .payment-buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
  }
}
</style>
